package com.element.oauth2.resource.config;

import com.element.oauth2.resource.context.TokenContext;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;

import javax.servlet.http.HttpServletRequest;

public class GlobalBearerTokenResolver implements BearerTokenResolver {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final PermitAllUrlProperties permitAllUrlProperties;

    public GlobalBearerTokenResolver(PermitAllUrlProperties permitAllUrlProperties) {
        this.permitAllUrlProperties = permitAllUrlProperties;
    }

    @Override
    public String resolve(HttpServletRequest request) {
        String url = request.getServletPath();
        if (StringUtil.isNullOrEmpty(url)) {
            return null;
        }
        if (permitAllUrlProperties.hasMatcher(url)) {
            return null;
        }
        try {
            return TokenContext.getToken(request);
        } catch (Exception e) {
            logger.error("解析请求中token异常:", e);
            return null;
        }
    }
}